<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools title="总记录数据20条">
        <el-button
          v-if="$store.state.user.userInfo.roles.points.includes('import_excel')"
          type="warning"
          size="small"
          @click="$router.push('/import')"
        >excel导入</el-button>
        <el-button
          v-if="$store.state.user.userInfo.roles.points.includes('export_excel')"
          type="danger"
          size="small"
          @click="hExport"
        >excel导出</el-button>
        <el-button
          type="primary"
          size="small"
          @click="showDialog = true"
        >新增员工</el-button>
      </PageTools>
      <el-card style="margin-top: 10px">
        <el-table border :data="list" :default-sort="{ prop: 'workNumber' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(scope.row)"
              >分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :total="total"
            :current-page="page"
            :page-sizes="[2, 5, 10]"
            :page-size="size"
            layout="sizes,prev, pager, next"
            @size-change="hSizeChange"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      title="新增员工"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <EmpDialog
        v-if="showDialog"
        @close="showDialog = false"
        @success="hSuccess"
      />
    </el-dialog>
    <el-dialog
      :visible.sync="showDialogRole"
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <AssignRole
        v-if="showDialogRole"
        :cur-id="curId"
        @close="showDialogRole = false"
      />
    </el-dialog>
  </div>
</template>

<script>
// import PageTools from '@/components/PageTools/index.vue'
import { TYPE_MAP } from '@/constant/index'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmpDialog from './EmpDialog.vue'
import AssignRole from './AssignRole'
export default {
  // components:{
  //   //  PageTools
  // }
  components: {
    EmpDialog,
    AssignRole
  },
  data() {
    return {
      list: [],
      total: 0,
      size: 2, //
      page: 1, // 页码
      showDialog: false, // 添加员工
      showDialogRole: false, // 设置角色
      curId: ''
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    hAssignRole({ id }) {
      console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.curId = id
    },
    hSuccess() {
      this.showDialog = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeeList()
    },
    async doDel(id) {
      await delEmployee(id)
      if (this.list.length === 1) {
        if (this.page > 1) {
          this.page--
        }
      }
      this.$message.success('删除成功')
      this.loadEmployeeList()
    },
    hDel(id) {
      this.$confirm('确认要删除吗?', '系统删除')
        .then(() => {
          this.doDel(id)
        })
        .catch(() => {})
    },
    hSizeChange(curPagesize) {
      console.log('curPagesize', curPagesize)
      // 1.更新参数
      this.size = curPagesize
      this.page = 1
      // 2.重发请求
      this.loadEmployeeList()
    },
    // 自动接收当前页码
    hCurrentChange(curPage) {
      // console.log(curPage);
      // 1.更新页码
      this.page = curPage
      // 2.重发请求
      this.loadEmployeeList()
    },
    format(type) {
      return TYPE_MAP[type] || '未知'
    },
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        // console.log(res);
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    formatData(rows) {
      const enHeader = Object.keys(rows[0])
      const mapObj = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      const header = enHeader.map((en) => mapObj[en])
      const data = rows.map((obj) => {
        obj.formOfEmployment = TYPE_MAP[obj.formOfEmployment]
        return Object.values(obj)
      })
      return { header, data }
    },
    hExport() {
      import('@/vendor/Export2Excel').then(async(excel) => {
        // excel表示导入的模块对象
        const res = await getEmployeeList(this.page, this.size)
        const list = res.data.rows
        console.log('从后端获取的数据', list)
        const { header, data } = this.formatData(list)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    }
  }
}
</script>
